/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author mwh
 */
public class FertilityTableCache implements FertilityTable {

    FertilityTable table;

    Map<Integer, List<Double>> cache;


    public FertilityTableCache(FertilityTable table, int size) {
        this.table = table;

        final long maxsize = Math.round(size * 0.80);

        cache = new LinkedHashMap<Integer, List<Double>>(size, 0.75F, true) {

            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, List<Double>> eldest) {

                return size() > maxsize;
            }
        };
    }


    public double get(int word, int fert) {
        List<Double> ferts = get(word);
//System.err.println("FERTS " + ferts + "  w: " + word) ;
        if (ferts.size() > fert) {
            return ferts.get(fert);
        }
        return Double.NaN;

    }


    public List<Double> get(int word) {
        List<Double> ferts = cache.get(word);
        if (ferts == null) {
            ferts = table.get(word);
            cache.put(word, ferts);
        }
        return ferts;
    }


    public double getLog10(int word, int fert) {
        return Math.log10(get(word, fert));
    }
}
